package com.gmall.user.server.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmall.common.enums.HttpBizCode;
import com.gmall.common.model.Response;
import com.gmall.common.util.BeanMapper;
import com.gmall.common.util.KeyUtils;
import com.gmall.user.api.po.Company;
import com.gmall.user.api.po.Role;
import com.gmall.user.api.po.User;
import com.gmall.user.api.po.UserInfo;
import com.gmall.user.api.vo.ResourceVo;
import com.gmall.user.server.redis.CacheManager;
import com.gmall.user.server.service.*;
import com.gmall.user.server.utils.GeneratorHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Project:gmall-user
 * File: com.gmall.user.server
 *
 * @author : lh.Wu
 * @date : 2019/12/3
 * Copyright 2006-2019 gmall Co., Ltd. All rights reserved.
 */
@Component
@Slf4j
public class UserBiz {

    private final UserService userService;

    private final RoleService roleService;

    private final ResourceService resourceService;

    private final CompanyService companyService;

    private final UserInfoService userInfoService;

    @Autowired
    private CacheManager cacheManager;

    public UserBiz(RoleService roleService,
                   UserService userService,
                   ResourceService resourceService,
                   CompanyService companyService,
                   UserInfoService userInfoService
    ) {
        this.roleService = roleService;
        this.userService = userService;
        this.resourceService = resourceService;
        this.companyService = companyService;
        this.userInfoService = userInfoService;
    }

    @Transactional
    public int saveUserInfo(JSONObject jsonObject){
        int i = 0;
        try {
            // 为个人账户、公司账户
            User user = BeanMapper.map(jsonObject, User.class);
            if(StringUtils.isEmpty(user.getId())){
                // 初始化id
                user.setId(GeneratorHelper.GENERATOR.nextId());
            }
            if(user.getType() == 0){
               // 个人
                UserInfo userInfo = BeanMapper.map(jsonObject,UserInfo.class);
                userInfo.setId(GeneratorHelper.GENERATOR.nextId());
                // 保存个人信息
                userInfoService.save(userInfo);
                user.setUserInfoId(String.valueOf(userInfo.getId()));
                cacheManager.set(KeyUtils.userInfoByUserId(String.valueOf(user.getId())), JSONObject.toJSONString(userInfo));
            }else{
                Company company =  BeanMapper.map(jsonObject,Company.class);
                company.setId(GeneratorHelper.GENERATOR.nextId());
                if(StringUtils.isEmpty(jsonObject.getString("logo"))){
                    company.setLogo(jsonObject.getString(""));
                }
                // 保存公司信息
                companyService.save(company);
                user.setCompanyId(String.valueOf(company.getId()));
                cacheManager.set(KeyUtils.userInfoByUserId(String.valueOf(user.getId())), JSONObject.toJSONString(company));
            }
            i = userService.save(user);
        } catch (Exception e) {
            log.error("save user occur error {}",e);
        }
        return i;
    }

    /**
     * 根据用户id 查询用户所有角色信息
     *
     * @param userId
     * @return
     */
    public Response<JSONObject> getAccountInfo(String userId){
        JSONObject jsonObject = new JSONObject();
        Response<JSONObject> response = Response.newInstance();
        // 查询用户类型
        User user = userService.findById(userId);
        if(user.getType() == 1){
            // 公司 查询公司详情
            Company company = companyService.findById(user.getCompanyId());
            BeanUtils.copyProperties(user,company);
            company.setAvatar(company.getLogo());
            jsonObject.put("user",company);
        }else{
            // 个人 查询个人详情
            UserInfo userInfo = userInfoService.findById(user.getUserInfoId());
            BeanUtils.copyProperties(user,userInfo);
            jsonObject.put("user",userInfo);
        }
        // 查询用户所有角色信息
        List<Role> rolesInfo = roleService.getRoleByUserId(userId);
        List<String> roles = new ArrayList<>();
        Optional.ofNullable(rolesInfo).ifPresent(roles1 -> roles1.stream().forEach(e -> roles.add(e.getCode())));
        jsonObject.put("role",roles);

        // 查询用户所有（目录、菜单）权限
        List<ResourceVo> resources = getResource(userId,0,0);
        jsonObject.put("resources",resources);
        response.fill(HttpBizCode.SUCCESS,HttpBizCode.SUCCESS.getText(),jsonObject);
        log.info("come in user id is \n {}",JSON.toJSONString(response));
        return response;
    }

    public List<ResourceVo> getResource(String userId,Integer type, Integer sourceId){
        // 查询所有目录
        List<ResourceVo> resources = resourceService.getResourceByUserId(userId,type,sourceId);
        // 查询所有二级目录
        Optional.ofNullable(resources).ifPresent(list -> list.stream().forEach(resource -> {
            // 查询所有目录、菜单
            List<ResourceVo> r1 = getResource(userId,9, (Integer) resource.getId());
            resource.setResources(r1);
        }));
        return resources;
    }

    public static void main(String[] args) {
        Company company = new Company();
        company.setUsername("张三");
        company.setName("希奥信息科技股份有限公司");
        company.setNickName("杨清风");
        company.setType(1);
        company.setPassword("123456");
        company.setAvatar("https://sioo-store.oss-cn-shanghai.aliyuncs.com/paas-system/logo.png");
        company.setAddress("上海市浦东新区春晓路439号");
        company.setContacts("希奥信息");
        company.setCategory(1);
        company.setStatus(0);
        company.setEmail("whl1789015971@163.com");
        company.setMobile("13693545265");
        company.setStockCode("2563125255412");
        company.setIsDeleted(0);
        log.debug("[{}]",JSON.toJSONString(company));

        System.out.println("----------------------------------------------");

        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("ldd");
        userInfo.setAddress("上海市浦东新区五洲大道思学路");
        userInfo.setAvatar("https://sioo-store.oss-cn-shanghai.aliyuncs.com/paas-system/logo.png");
        userInfo.setCategory(1);
        userInfo.setContacts("张无忌");
        userInfo.setPassword("123456");
        userInfo.setEmail("hlwu178901971@gmail.com");
        userInfo.setPhone("13693542984");
        userInfo.setCompanyId("11726551357147136");
        userInfo.setType(0);
        userInfo.setNickName("张无忌");
        userInfo.setIsDeleted(0);

        log.debug("[{}]",JSON.toJSONString(userInfo));
    }
}
